package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessHistoryMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.model.po.MediaProcessHistory;
import com.xuecheng.media.service.MediaFileProcessService;
import com.xuecheng.media.service.MediaFileService;
import com.xuecheng.media.service.MediaProcessHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * create 2023/5/7 21:35
 */

@Service
@Slf4j
public class MediaFileProcessServiceImpl extends ServiceImpl<MediaProcessMapper,MediaProcess> implements MediaFileProcessService {

    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    @Autowired
    private MediaFileService mediaFileService;

    @Autowired
    private MediaProcessHistoryService mediaProcessHistoryService;
    @Override
    public List<MediaProcess> selectProcessByShardIndex(Integer shardIndex, Integer totalShardNum, Integer processNum) {
        return mediaProcessMapper.selectProcessByShardIndex(shardIndex, totalShardNum, processNum);
    }

    @Transactional
    @Override
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errorMsg) {
        MediaProcess mediaProcess = this.getById(taskId);
        if (mediaProcess == null) {
            log.error("该处理任务不存在,任务Id：{}", taskId);
            return;
        }
        //任务执行失败，更新待处理任务表的记录状态、失败信息
        mediaProcess.setStatus(status);
        mediaProcess.setErrormsg(errorMsg);
        mediaProcess.setFinishDate(LocalDateTime.now());
        this.updateById(mediaProcess);
        if (status.equals("3")) {
            //处理失败,不用写入历史表
            return;
        }
        //任务执行成功,保存url到待处理任务表，
        mediaProcess.setUrl(url);
        //更新media_files的url，
        MediaFiles mediaFiles = mediaFileService.getById(fileId);
        mediaFiles.setUrl(url);
        mediaFileService.updateById(mediaFiles);

        //复制到处理历史表，
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        mediaProcessHistoryService.save(mediaProcessHistory);

        //最后删除待处理任务表的记录
        this.removeById(taskId);

    }
}
